package com.sp.aspect;

import com.sp.exception.BusinessException;
import com.sp.exception.TokenException;
import com.sp.model.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author tong
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 系统错误状态码
     */
    public static final Integer SYSTEM_ERROR = 500;

    public static final String SYSTEM_ERROR_MESSAGE = "系统繁忙，请稍后重试！";

    /**
     * 解决 GlobalExceptionHandler 会消费掉 AccessDeniedException，导致 AccessDeniedHandler 不会被触发的问题.
     *
     * @param accessDeniedException
     * @throws AccessDeniedException
     */
    @ExceptionHandler(AccessDeniedException.class)
    public void accessDeniedException(AccessDeniedException accessDeniedException) throws AccessDeniedException {
        throw accessDeniedException;
    }

    /**
     * 处理业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Object> businessExceptionHandler(Exception e) {
        // 处理业务异常，直接返回错误码
        e.printStackTrace();
        return Result.error(e.getMessage());
    }

    /**
     * 处理token异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(TokenException.class)
    public Result<Object> tokenExceptionHandler(Exception e) {
        // 处理token异常，直接返回错误码403
        e.printStackTrace();
        return Result.error(e.getMessage(), HttpStatus.FORBIDDEN.value());
    }

    /**
     * 处理其它异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler
    public Result<Object> exceptionHandler(Exception e) {
        // 处理逻辑异常，打印日志
        log.error("异常信息");

        e.printStackTrace();
        return Result.error(SYSTEM_ERROR_MESSAGE, SYSTEM_ERROR);
    }

}
